package nd.privatebrowser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class PrivateBrowserActivity extends Activity {

	private static final int MENU_SELECT_TEXT_ID = Menu.FIRST;
	private static final int MENU_TOR_APP_SETTINGS_ID = Menu.FIRST + 1;
	private static final int MENU_BACK_MENU_ID = Menu.FIRST + 2;
	private static final int MENU_CLEAR_HISTORY_ID = Menu.FIRST + 3;
	private static final int DIALOG_TOR_INSTALL_ID = 0;
	private static final int DIALOG_TOR_ASK_START_ID = 1;
	private EditText edittext;
	private WebView mWebView;
	private Button goButton;
	private BrowserContext browser;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        edittext = (EditText) findViewById(R.id.urledit);
        goButton = (Button) findViewById(R.id.gobutton);
                
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.setWebViewClient(new HelloWebViewClient());
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBlockNetworkImage(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setLoadsImagesAutomatically(false);
        mWebView.getSettings().setAllowFileAccess(false);
        
        if(browser == null) {
//        	Toast.makeText(PrivateBrowserActivity.this, "Warning! new BrowserContext", Toast.LENGTH_SHORT).show();        	
        	browser = new BrowserContext(this);
        }
//        if (savedInstanceState != null) {
//        	browser.load(savedInstanceState);
//        	updateWebView();
//        }
        
        final Button goButton = (Button) findViewById(R.id.gobutton);
        goButton.setOnClickListener( new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				if(browser.isLoadingInProgress()) {
					browser.cancelTask();
				} else {
					goToUrl(edittext.getText().toString());
				}
			}
			
		});
        
        edittext.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                    (keyCode == KeyEvent.KEYCODE_ENTER)) {
                  // Perform action on key press
                	goToUrl(edittext.getText().toString());
                  return true;
                }
                return false;
            }
        });

        setHomePage();
        
        checkConnetion();
        
    }

	private void checkConnetion() {
		new Thread(new Runnable() {
		    public void run() {
		    	final boolean connectionCheck = BrowserUtil.checkTorConnection();
		    	if(connectionCheck == false) {
			    	runOnUiThread(new Runnable() {
			    		public void run() {
			    			askToStartTor();
			    		}
			    	});
		    	}
		    }
		}).start();

	}

	private void setHomePage() {
		edittext.setText("https://check.torproject.org/");
//      edittext.setText("http://");
		
	}

    private void goToUrl(String url) {
    	//hide keyboard
    	InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);

    	PageLoaderTask task = new PageLoaderTask(PrivateBrowserActivity.this, url);
    	browser.startTask( task );
    	    	
	}
        
//    @Override
//	protected void onSaveInstanceState(Bundle outState) {
//		super.onSaveInstanceState(outState);
//		browser.saveState(outState);		
//	}
    
    private void updateWebView() {
		mWebView.loadDataWithBaseURL(null, browser.getContent(), 
				"text/html", 
				"utf-8", null);
		mWebView.clearHistory();
		mWebView.clearCache(true);
	}
    
    public void updateGoButtonText(boolean taskFinished) {
		if( browser.isLoadingInProgress() && taskFinished == false) {
			goButton.setText(R.string.go_button_stop);
		} else {
			goButton.setText(R.string.go_button);
		}
	}
    
    public void updateUrlField() {
    	edittext.setText(browser.getRenderedUrl());    	
		updateWebView();
				
//		Toast.makeText(PrivateBrowserActivity.this, "Warning! updateUrlField"+isFinishing(), Toast.LENGTH_SHORT).show();
	}
        
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	// needs to save activity on screen rotation
      super.onConfigurationChanged(newConfig);
    }

	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
		
        if ((keyCode == KeyEvent.KEYCODE_BACK) && browser.hasHistory()) {        	
        	browser.goBack();        	
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    
    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {        	
        	goToUrl(url);            
            return true;
        }

		@Override
		public void onLoadResource(WebView view, String url) {

			Toast.makeText(PrivateBrowserActivity.this, "Warning! resource loaded without Tor: "+url, Toast.LENGTH_SHORT).show();

		}                
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_BACK_MENU_ID, 0, R.string.menu_back);
        menu.add(0, MENU_SELECT_TEXT_ID, 10, R.string.menu_select_text);
        menu.add(0, MENU_CLEAR_HISTORY_ID, 20, R.string.menu_clear_history);
        menu.add(0, MENU_TOR_APP_SETTINGS_ID, 30, R.string.menu_tor_connect);
        return true;
    }
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case MENU_SELECT_TEXT_ID:
                selectText();
                return true;
            case MENU_TOR_APP_SETTINGS_ID:
            	startTor();
            	return true;
            case MENU_CLEAR_HISTORY_ID:
            	browser.clearWindowAndHistory();
            	setHomePage();
            	updateWebView();
            	return true;
            case MENU_BACK_MENU_ID:
            	if (browser.hasHistory()) {        	
                	browser.goBack();        	
                    return true;
                }
            	return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }    


	private void startTor() {
//		Toast.makeText(PrivateBrowserActivity.this, "startTor", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent("org.torproject.android.START_TOR");
		try {
			startActivity(intent);
		} catch (ActivityNotFoundException e) {
//			Toast.makeText(PrivateBrowserActivity.this, "Orbot wasn't found", Toast.LENGTH_SHORT).show();
			showDialog(DIALOG_TOR_INSTALL_ID);
		}
	}

	private void selectText() {
//		Toast.makeText(PrivateBrowserActivity.this, "select text", Toast.LENGTH_SHORT).show();
		KeyEvent shiftPressEvent = new
			KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0);
		shiftPressEvent.dispatch(mWebView); 
	}
		

	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id) {
		case DIALOG_TOR_INSTALL_ID:
			return buildDialogTorInstall();
		case DIALOG_TOR_ASK_START_ID:			
			return buildDialogAskStartTor();
		}
		return null;
	}

	private AlertDialog buildDialogAskStartTor() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.tor_not_started)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   startTor();
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		return alert;
	}

	private AlertDialog buildDialogTorInstall() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.tor_not_installed)
//			       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   openTorInMarket();
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		return alert;
	}

	protected void openTorInMarket() {
//		Toast.makeText(PrivateBrowserActivity.this, "install Tor", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(Intent.ACTION_VIEW, 
				Uri.parse("market://search?q=pname:org.torproject.android"));
		try {
			startActivity(intent);
		} catch(ActivityNotFoundException e) {
			Toast.makeText(PrivateBrowserActivity.this, "Please, install Tor on Android(Orbot) manually", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onPause() {
		// nothing to save for now
		super.onPause();
	}
	
	

	@Override
	protected void onDestroy() {
//		Toast.makeText(PrivateBrowserActivity.this, "Warning! "+isFinishing(), Toast.LENGTH_SHORT).show();
		if ( isFinishing()) {
			browser.cancelTask();
		}
		
		super.onDestroy();
	}

	public BrowserContext getBrowser() {
		return browser;
	}

	public void askToStartTor() {
		showDialog(DIALOG_TOR_ASK_START_ID);		
	}
        
}